import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodName:'',
    goodType:1,
    goodSpec:'',
    goodPrice:'',
    goodDiscount:'',
    imgUrl:'',
    bannerList:[],
    detailBannerList:[],
    goodDesc:'',
    goodDetailDesc:'',
    uploading:false
  },
  getters: {
    canSubmit(state){
      return state.imgUrl!=''&&state.goodDiscount!=''&&state.goodName!=''&&state.goodPrice!=''&&state.goodSpec!=''
    }
  },
  mutations: {
    setNewValue(state,params){
      state[params.prop] = params.newValue
    },
    addBanner(state,url){
      if(state.bannerList.length>=3)
        return
      state.bannerList.push(url)
    },
    delBanner(state,index){
      Vue.delete(state.bannerList,index)
    },
    addDetailBanner(state,url){
      if(state.detailBannerList.length>=3)
        return
      state.detailBannerList.push(url)
    },
    delDetailBanner(state,index){
      Vue.delete(state.detailBannerList,index)
    },
    resetAll(state){
      state.goodName = ''
      state.goodType = 1
      state.goodSpec = ''
      state.goodPrice = ''
      state.goodDiscount = ''
      state.imgUrl = ''
      state.bannerList = []
      state.detailBannerList = []
      state.goodDesc = ''
      state.goodDetailDesc = ''
      state.uploadGood = false
    },
    async uploadGood(state){
      if(state.uploadGood)
        return
      state.uploading = true      
      let {data:ret} = await Vue.prototype.$http.post('/uploadGood',{
        goodName:state.goodName,
        goodType:state.goodType,
        goodSpec:state.goodSpec,
        goodPrice:state.goodPrice,
        goodDiscount:state.goodDiscount,
        goodIcon:state.imgUrl,
        goodDesc:state.goodDesc,
        bannerList:state.bannerList,
        detailBannerList:state.detailBannerList,
        goodDetailDesc:state.goodDetailDesc,
      })
      if(ret.affectedRows>0){
        this.commit('resetAll')
        alert('添加货物成功')
        state.uploading = false
      }
    }
  },
  actions: {
  },
  modules: {
  },
  setter:{
    goodType(state,newValue){
      state.goodType = newValue
    }
  }
})
